__author__ = 'shawhen'

from PyQt5.QtCore import *


def prepare(version="jre7", arch="auto", dst_dir="./", do_what_cb = None):
    """
    如果是系统java，则返回: (sys, java)
    否则返回(custom, 部署好的java组件的路径, 不含dst_dir前缀)
    :param arch: i386 or amd64 (auto: 32位系统即部署32位java，64位系统即部署64位java)
    """
    import subprocess
    import os

    from .. import dummy_honeycomb as m_dummy_honeycomb
    from .. import ue_fly as m_ue

    m_ue.prepare_common_components()

    checking_sys_java = "正在检查系统java组件"
    select_java = "正在适配java组件"
    deploy_java = "正在部署java组件"

    if do_what_cb is not None:
        dummy_honeycomb = m_dummy_honeycomb.DummyHoneyComb()
        dummy_honeycomb.sigProcessing.connect(do_what_cb)
        dummy_honeycomb.emit_processing(checking_sys_java, "N/A", 10, 0)

    from ..platform import what as m_what_platform
    running_os = m_what_platform.running_os

    sys_java_path = "java"
    check_java_process_output = b""
    try:
        check_java_process = subprocess.Popen("java -version", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, check_java_process_output = check_java_process.communicate(timeout=3)
    except (FileNotFoundError, subprocess.TimeoutExpired):
        if running_os["type"] == "windows" and running_os["arch"] == "amd64":  # windows 64位，需要访问一下真实的System32
            try:
                check_java_process = subprocess.Popen("c:/Windows/SysNative/java -version", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                # 它为什么输出到stderr。。说实话，我也很纳闷
                stdout, check_java_process_output = check_java_process.communicate(timeout=5)
                sys_java_path = "c:/Windows/SysNative/java"
            except Exception:
                pass

    if b"java version" in check_java_process_output and b"1."+version[3:].encode() in check_java_process_output:  # 版本匹配
        if running_os["arch"] == "amd64" and arch == "auto":  # 64位系统的自动适配，就是需要系统java为64位
            if b"64-Bit" in check_java_process_output:
                return ("sys", sys_java_path)
    dummy_honeycomb.emit_processing(checking_sys_java, "N/A", 100, 0)

    dummy_honeycomb.emit_processing(select_java, "N/A", 11, 0)
    manifest_platform = None
    if running_os["type"] == "windows":
        if arch != "auto":
            if arch == "i386":
                manifest_platform = "win32"
            elif arch == "amd64":
                manifest_platform = "win64"
        else:  # 自动适配合适的java位数
            if running_os["arch"] == "i386":
                manifest_platform = "win32"
            elif running_os["arch"] == "amd64":
                manifest_platform = "win64"
    else:
        raise NotImplementedError

    dummy_honeycomb.emit_processing(select_java, "N/A", 36, 0)
    manifest_module = None
    locals = {}
    exec("from cburanome.uranome.component.java.{0}.{1} import manifest as manifest_module"
         .format(version, manifest_platform), globals(), locals)
    manifest_module = locals["manifest_module"]
    dummy_honeycomb.emit_processing(select_java, "N/A", 100, 0)

    mnifest_patch_module = None
    exec("from cburanome.uranome.component.java.{0}.{1} import manifest_patch as manifest_patch_module"
         .format(version, manifest_platform), globals(), locals)
    manifest_patch_module = locals["manifest_patch_module"]

    java_ue = m_ue.UranomeUpdateEngine()
    java_ue.set_doing_translate({"downloading": deploy_java, "checking": deploy_java, "extracting": deploy_java})
    java_ue.sigProcessing.connect(do_what_cb)
    java_ue.add_manifest(manifest_module.manifest, manifest_module.base_url)
    java_ue.add_patch(manifest_patch_module.manifest, manifest_patch_module.base_url)
    java_ue.start("./", dst_dir)
    return ("custom", "java")